<?php

namespace app\service;

use app\model\Post as PostModel;
use support\ErrorCode;

class PostBatch
{

    /**
     * 批量添加工序-给SASS后台提供的接口
     * @param $data
     * @return int|void
     * @throws \exception
     */
    public function bathCreatePost($data)
    {

        if (!empty($data['posts'])) {
            try {
                $pid = 0;
                foreach ($data['posts'] as $v) {
                    $v['type']         = $data['type'] ?? '';
                    $v['user_id']      = $data['user_id'] ?? '';
                    $v['tenant_id']    = $data['tenant_id'] ?? '';
                    $v['book_type_id'] = $data['book_type_id'] ?? '';
                    $this->savePost($v, $pid);
                }
                unset($this->pId);
                unset($postModel);
                return $pid;
            } catch (\Exception $e) {
                throw_strack_exception($e->getMessage(), ErrorCode::CREATE_BATCH_POST_FAILURE);
            }
        }
    }

    public function savePost($value, &$pid)
    {
        $isExitTitle = PostModel::where(['name' => $value['name'], 'parent_id' => $pid, 'book_type_id' => $value['book_type_id']])->find();
        if ($isExitTitle) {
            $pid = $isExitTitle->id;
            return false;
        } else {
            $postModel = PostModel::create([
                'name' => $value['name'],
                'type' => 'catalog_post',
                'content' => $value['content'],
                'parent_id' => $pid ?? 0,
                'file_type' => $value['file_type'],
                'created_by' => $value['user_id'],
                'book_type_id' => $value['book_type_id'],
            ]);
            $pid = $postModel->id;
            return true;
        }
    }

    /**
     * 批量同步树结构
     */
    public function bathSyncParentId()
    {
        // 查出需要同步的数据
        $postModel = PostModel::join('catalog', 'post.catalog_id = catalog.id and post.item_id = catalog.item_id', 'LEFT')
            ->where("post.item_id !='' and post.catalog_id !='' and catalog.parent_id !=''")
            ->field('post.id,catalog.parent_id')
            ->select();
        if (!$postModel->isEmpty()) {
            $postData = $postModel->toArray();
            // 批量修改post 表 parent_id
            $postModel = new PostModel();
            $postModel->saveAll($postData);
        }
    }

}